import {
  Component,
  ViewEncapsulation,
  ChangeDetectionStrategy,
  forwardRef,
  ChangeDetectorRef,
  SimpleChanges,
  Input,
  OnInit,
  OnChanges,
} from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { CalendarBaseComponent } from '../core/calendar-base/calendar-base.component';
import { I18NService, DateService, StandardDate, InputBoolean } from '../core/api';

@Component({
  selector: 'lv-date-picker-10year',
  templateUrl: './date-picker-10year.component.html',
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef((): typeof DatePicker10YearComponent => DatePicker10YearComponent),
      multi: true,
    },
  ],
  host: {
    class: 'lv-date-picker-10year',
  },
})
export class DatePicker10YearComponent extends CalendarBaseComponent implements OnInit, OnChanges {
  @Input() @InputBoolean() lvOnlyShowActiveCell = false; // 是否显示上100年、下100年的单元格

  activeDateYearRange;

  constructor(
    public cdr: ChangeDetectorRef,
    public dateService: DateService,
    public i18n: I18NService,
  ) {
    super(cdr, dateService);
    this.prefixCls = 'lv-date-picker-10year';
  }

  trackByIndex(index): any {
    return index;
  }

  ngOnInit(): void {
    this.renderCalendar10YearUI();
  }

  selectCalendarYearCell(cell): void {
    this.doSelect(cell.value);
  }

  renderCalendar10YearUI(): void {
    this.renderCalendarYearHeader();
    this.renderCalendar({ show10YearsPanel: true });
  }

  addYear(num): void {
    this.activeDate = new StandardDate(this.activeDate.addYears(num));
    this.renderCalendar10YearUI();
  }

  doSelect(value): void {
    this.value = new StandardDate(value);
    this.valueChange.emit(this.value);
    this.renderCalendar10YearUI();
  }

  renderCalendarYearHeader(): void {
    this.activeDateYearRange = `${this.activeDate.getYear() - (this.activeDate.getYear() % 100)} - ${
      this.activeDate.getYear() - (this.activeDate.getYear() % 100) + 99
    }`;
  }

  ngOnChanges(changes: SimpleChanges): void {
    const flag =
      changes.lvActiveDate ||
      this.isDateChange(changes.value) ||
      this.isDateChange(changes.selectedValue) ||
      this.isDateChange(changes.hoverValue);
    if (flag) {
      this.lvActiveDate && (this.activeDate = this.lvActiveDate);
      this.renderCalendar10YearUI();
    }
  }
}
